import {
  asyncRoutes,
  constantRoutes
} from '@/router'

import store from '../../store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    /* includes() 方法用来判断一个数组是否包含一个指定的值，如果是返回 true，否则false。 */
    return route.meta.roles.includes(roles)
    // return;
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route
    }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: constantRoutes,
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({
    commit
  }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      let arr = []
      let team = store.state.team.teamId ? store.state.team.teamId : ''
      if (roles === 'visitor' || roles === 'admin') {
        accessedRoutes = asyncRoutes || []
      } else if (roles === 'readOnly' || roles === 'manager' || roles === 'advManager'){
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        accessedRoutes = accessedRoutes.map(item => {
          if (!item.children || item.children.length < 1) {
            item.alwaysShow = false;
            item.hidden = true
          }
          if (roles === 'manager' && item.path === '/ad') {
            item.children = item.children.map(v => {
              // if (v.path === 'create') {
              //   v.hidden = true
              // }
              // if (v.name === 'create_team')
              return v
            })
          }
          return item
        })
      } else if (!team || !roles) {
        asyncRoutes.map(element => {
          let {children, ...param} = element
          arr.push(param)
        })
        arr[2].children = [
          {
            path: 'create_team',
            name: 'create_team',
            hidden: true,
            component: () => import('@/views/user/user-manager/create_team'),
            meta: {
              title: '创建团队',
              keepAlive: false,
              roles: ['visitor']
            }
          }
        ]
        accessedRoutes = arr
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
/* // const roles=['系列管理员','账号财务','系列只读']
  游客：visitor:拥有所有权限及路由
  系列管理员：manager:除了(创建广告系列+财务)外的所有权限+路由
  账号财务：finance:除了公共页面之外 只能进入财务页面
  账号只读+账号只读：readOnly:除了公共页面之外，只能进入数据概览页面&&只有查询及导出功能 */
